import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { CacheService } from '../../../core/routes-services/cache.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { MyModalHelper } from '../../../core/my-modal.helper';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../constant/config';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MarketBandService } from '../../../core/routes-services/market-band.service';

@Component({
  selector: 'app-market-band-edit',
  templateUrl: './market-band-edit.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 128px;
      height: 128px;
    }

    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }

    :host ::ng-deep .ant-upload .avatar {
      width: 120px;
      height: 120px;
    }
  `],

})
export class MarketBandEditComponent implements OnInit {
  id: number = 0;
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};
  componentDirty: boolean = false;
  @ViewChild('content') content: ElementRef;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private modalHelper: MyModalHelper,
              public marketBandService: MarketBandService,
              private message: NzMessageService,
              private cacheService: CacheService,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    this.route.queryParams.forEach((params: Params) => {
      this.id = +params['id'];
      this.initEntity();
    });
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.initValidateForm();
  }

  initEntity() {
    if (this.id != 0) {
      this.marketBandService.detail(this.id).then((res) => {
        console.log(res);
        if (res.status.toString().startsWith('20')) {
          this.entity = res.data;
          this.initValidateForm();
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  initValidateForm() {
    this.validateForm = this.fb.group({
      title: [this.entity.title, [Validators.required, Validators.maxLength(60)]],
      sortNum: [this.entity.sortNum, [Validators.required]],
      mainImg: [this.entity.mainImg, [Validators.required]],
      description: [this.entity.description, [Validators.required]],
    });
    this.content.nativeElement.innerHTML = this.entity.description ? this.entity.description : '点击进行内容编辑';
  }

  isShow: boolean = false;

  showEdit() {
    this.isShow = !this.isShow;
    let body = document.body;
    if (this.isShow) {
      body.style.overflow = 'hidden';
      body.style.userSelect = 'none';
    } else {
      body.style.overflow = '';
      body.style.userSelect = '';
    }
  }

  contentCallback(content) {
    this.entity.description = content;
    this.content.nativeElement.innerHTML = this.entity.description;
    this.componentDirty = true;
    this.validateForm.controls.description.setValue(content);
  }

  submitForm() {
    let $this = this;
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {

      //保存修改
      if (this.validateForm.dirty || this.componentDirty) {
        this.isLoading = true;
        this.marketBandService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.message.success('保存成功');
            this.entity = res.data;
            this.goBack();
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });

      }else {
        //无操作直接返回
        this.goBack();
      }
    }
  }

  goBack() {
    this.router.navigate(['/band/list']);
  }

  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.mainImg = fileList[findIdx].url;
      this.validateForm.controls.mainImg.setValue(this.entity.mainImg);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }
}
